package cn.virens.common.boot.provider.apijson;

import apijson.orm.AbstractParser;
import apijson.orm.AbstractVerifier;
import apijson.orm.SQLConfig;
import apijson.orm.Visitor;
import cn.virens.common.util.core.Assert;
import cn.virens.common.util.exception.APIException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Objects;

public class APIJSONVerifier extends AbstractVerifier<String, JSONObject, JSONArray> {
    private final APIJSONParser parser;

    public APIJSONVerifier(APIJSONParser parser) {
        this.parser = parser;
    }

    @Override
    public APIJSONVerifier setParser(AbstractParser<String, JSONObject, JSONArray> parser) {
        return this;
    }

    @Override
    public synchronized Visitor<String> getVisitor() throws APIException {
        if (visitor == null || parser == null) {
            this.setVisitor(new VirVisitor());
        }

        return visitor;
    }

    @Override
    public void verifyLogin() throws Exception {
        Assert.isNull(getVisitor(), "用户未登录");
    }

    @Override
    public APIJSONParser createParser() {
        return parser;
    }

    @Override
    public APIJSONParser getParser() {
        return parser;
    }

    @Override
    public APIJSONVerifier setVisitor(Visitor<String> visitor) {
        this.visitor = Objects.requireNonNull(visitor);
        this.visitorId = Objects.hashCode(visitor);

        return this;
    }

    @Override
    public boolean verifyAccess(SQLConfig cfg) throws Exception {
        return true;
    }
}
